<?php


namespace plugin\agent\app\admin\logic;


use app\common\logic\BaseLogic;
use app\common\service\ConfigService;
use plugin\agent\app\model\AgentOrder;
use support\Log;
use support\utils\Decimal;

class AgentOrderLogic extends BaseLogic
{
    private array $settlementMap;

    public function __construct()
    {
        $this->model = new AgentOrder();
    }

    public function settlement($time)
    {
        //查询
        $config = ConfigService::getConfig('AGENT_REBATE_CONFIG');
        $freeze_day = $config['freeze_day'];
        $create_time = date("Y-m-d H:i:s", strtotime("-{$freeze_day}day", strtotime($time)));
        $list = $this->model->where([
            ['create_time', '<=', $create_time],
            ['status', '=', AgentOrder::STATUS_WAIT_SETTLEMENT],
        ])
            ->select();
        if (!$list) {
            Log::channel("agent")->info("结算任务:未查询到需要结算的数据");
            return;
        }
        foreach ($list as $item) {
            $this->setSettlement($item['one_agent_id'], $item['one_amount']);
            $this->setSettlement($item['two_agent_id'], $item['two_amount']);
            $this->setSettlement($item['three_agent_id'], $item['three_amount']);
        }
        $this->transaction(function () use ($create_time) {
            //发放用户余额

            $this->model->where([
                ['create_time', '<=', $create_time],
                ['status', '=', AgentOrder::STATUS_WAIT_SETTLEMENT],
            ])
                ->update([
                    'status' => AgentOrder::STATUS_SETTLEMENTED
                ]);

        });

        $this->settlementMap = [];
    }

    private function setSettlement($user_id, $amount)
    {
        if (!isset($this->settlementMap[$user_id])) {
            $this->settlementMap[$user_id] = Decimal::newDecimal();
        }
        $this->settlementMap[$user_id]->add($amount);
    }
}